import {
  getErrorReportFileInfoByPage,
  addErrorReportFileInfo,
  updateErrorReportFileInfo,
  delErrorReportFileInfo,
  exportErrorReportFileInfo,
  getErrorReportFileInfoPageByErrorReportId,
  getErrorPreviewUrl,
  uploadErrorReportFileInfo,
} from '@/services/platform/errorReportFileInfo';
import { PlusOutlined, UploadOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Col, Form, Input, message, Modal, Row, Tree, Upload } from 'antd';
import { sortTran, filterTran, filterTranNew } from '@/utils/requestUtil';
import React, { useEffect, useRef, useState } from 'react';
import {
  ModalForm,
  ProFormItem,
  ProFormText,
  ProFormUploadButton,
} from '@ant-design/pro-components';
import FormItem from 'antd/es/form/FormItem';
import { viewBaseInfo } from '@/services/platform/errorReport';
import log from '@/services/system/log';
const ErrorReportFileInfo: React.FC<{}> = (props) => {
  const actionRef = useRef<ActionType>();
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [formTitle, setFormTitle] = useState('新建'); //
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable
  const [form] = Form.useForm();
  const ref = useRef(null);
  const [errorRecord, setErrorRecord] = useState([]); //父组件传入的异常处理详情
  const [status, setStatus] = useState(0); //表示网络请求状态，如果为1表示根据id请求，如果为0，表示获取所有的异常附件信息
  const [fileList, setFileList] = useState([]); //所上传的文件列表
  const [username, setusername] = useState([]);
  useEffect(() => {
    getuser(); //获取用户信息
    console.log('如果父组件传入的值反正改变，则进行页面刷新');
    console.log('父组件传入数据：', props.errorRecord);
    actionRef.current.reload(); //刷新附件列表
    if (props.errorRecord != undefined) {
      setErrorRecord(props.errorRecord);
    }
    if (props.errorRecord != undefined) {
      setStatus(1);
    } else {
      setStatus(0);
    }
  }, [props.errorRecord]);
  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 80,
      align: 'center',
      sorter: true,
    },
    {
      title: '文件名称',
      dataIndex: 'fileName',

      align: 'center',
      sorter: true,
    },
    // {
    //   title: '异常附件链接',
    //   dataIndex: 'attachmentUrl',
    // },
    // {
    //   title: '异常附件id',
    //   dataIndex: 'errorReportId',
    // },
    // {
    //   title: '文件编号',
    //   dataIndex: 'fileCode',
    //  align: 'center',sorter: true,
    // },
    {
      title: '上传日期', //表头显示的名称
      search: false,
      dataIndex: 'createTime',

      align: 'center',
      sorter: true,
    },
    {
      title: '上传人', //表头显示的名称
      search: false,
      dataIndex: 'createName',

      align: 'center',
      sorter: true,
    },
    {
      title: '操作',
      valueType: 'option',
      align: 'center',
      key: 'option',
      fixed: 'right',

      render: (text, record, _, action) => [
        // <a
        //   key="editKey"
        //   onClick={() => {
        //     setModalVisit(true);
        //     setCreateOrUpdate(true);
        //     setFormTitle('编辑');
        //     form.setFieldsValue({
        //       attachmentUrl: record.attachmentUrl,
        //       errorReportId: record.errorReportId,
        //       fileCode: record.fileCode,
        //       fileName: record.fileName,
        //       id: record.id,
        //     });
        //   }}
        // >
        //   编辑
        // </a>,
        <a
          key="editKey"
          onClick={async () => {
            console.log('记录：', record);
            const URl = await getErrorPreviewUrl(record);
            console.log('文件路径', URl);
            window.open(URl.message);
            // if (errorRecord?.fileName.includes('.pdf')) {
            //   //如果是pdf格式，则实现预览，如果不是，则下载
            //   //setModalVisit4(true);
            //   setConfirmLoading4(true);
            //   console.log('获取pdf文件路径：', URl.message);
            //   //setErrorPreview(URl.message);
            //   window.open(URl.message);
            // } else {
            //   window.open(URl.message);

            // downloadErrorReportFile({ errorReportId: errorRecord?.id }).then((res) => {
            //   const aLink = document.createElement('a');
            //   document.body.appendChild(aLink);
            //   aLink.style.display = 'none';
            //   aLink.href = window.URL.createObjectURL(res);
            //   aLink.setAttribute('download', `${errorRecord?.fileName}`);
            //   aLink.click();
            //   document.body.removeChild(aLink);
            // });
          }}
        >
          预览下载
        </a>,
        <a
          key="deleteKey"
          onClick={() => {
            Modal.confirm({
              title: '删除',
              content: '确定要删除吗',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                await delErrorReportFileInfo({ id: record.id });
                actionRef.current.reload();
              },
            });
          }}
          // hidden={username != errorRecord?.operator && username != errorRecord?.handlingMan}
          hidden={username != errorRecord?.operator}
        >
          删除
        </a>,
      ],
    },
  ];

  /* 方法 */

  /* 文件列表改变时，文件上传时触发 */
  const onFilesChange = (info: any) => {
    setFileList(info.fileList);
  };

  //获取：用户名（填报人）
  const getuser = async () => {
    const getuserlist = await viewBaseInfo(null);
    setusername(getuserlist.data.name);
    console.log('当前用户：', getuserlist.data.name);
  };

  /* 在文件上传之前进行检验 */
  const handleBeforeUpload = (info: any) => {
    // console.log('在文件上传之前进行检验', info);
    // //检验文件大小
    // if (info.size) {
    //   const isLt = info.size / 1024 / 1024 < 1000;
    //   if (!isLt) {
    //     alert(`上传文件大小不能超过 ${1} GB!`);
    //     return false;
    //   } else {
    //     //验证通过
    //   }
    // }
    //检验成功
    return false; //这里必须要返回false，来阻止原生的组件的默认action行为，不然会显示存储错误的信息
  };

  /* 上传附件 */
  const addErrorFile = async () => {
    form
      .validateFields()
      .then(async () => {
        const res = form.getFieldsValue();
        const formData = new FormData();
        res.file.fileList.map((file: any) => {
          formData.append('file', file.originFileObj);
        });
        res.file = formData;
        console.log('附件上传参数：', res);
        const result = await uploadErrorReportFileInfo(res);
        if (result != null) {
          message.success('异常新增成功');
        }
        setModalVisit(false);
        actionRef.current.reload();
      })
      .catch(() => {});
  };

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <ProTable
        headerTitle="异常附件查询"
        actionRef={actionRef} //用于触发刷新操作等，看api
        rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
        formRef={ref}
        search={status == 0}
        toolBarRender={(action, { selectedRows }) => [
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              setCreateOrUpdate(false);
              setFormTitle('附件上传');
              setModalVisit(true);
            }}
            type="primary"
          >
            附件上传
          </Button>,
          // <Button
          //   key="button"
          //   icon={<PlusOutlined />}
          //   onClick={() => {
          //     const filters = filterTranNew(ref.current.getFieldsValue());
          //     exportErrorReportFileInfo({
          //       current: 1,
          //       pageSize: 5000,
          //       filters: filters,
          //     }).then((res) => {
          //       const aLink = document.createElement('a');
          //       document.body.appendChild(aLink);
          //       aLink.style.display = 'none';
          //       aLink.href = window.URL.createObjectURL(res);
          //       aLink.setAttribute('download', `ErrorReportFileInfo.xlsx`);
          //       aLink.click();
          //       document.body.removeChild(aLink);
          //     });
          //   }}
          //   type="primary"
          // >
          //   导出
          // </Button>,
        ]}
        request={async (params, sort, filter) => {
          const sorters = sortTran(sort);
          const filters = filterTranNew(params);
          let result = [];
          if (status == 0) {
            //异常附件查询全部
            result = await getErrorReportFileInfoByPage({
              ...params,
              sorters: sorters,
              filters: filters,
              current: params.current,
              pageSize: params.pageSize,
            });
            result.data.content.map((item: any) => {
              item.createTime = item.createTime.split(' ')[0];
            });
          }
          if (status == 1) {
            //根据异常处理id来进行异常附件隔离
            const pageEntity = {
              sorters: sorters,
              filters: filters,
              current: params.current,
              pageSize: params.pageSize,
            };
            result = await getErrorReportFileInfoPageByErrorReportId({
              pageEntity: pageEntity,
              errorReportId: errorRecord.id,
            });
            result.data.content.map((item: any) => {
              item.createTime = item.createTime.split(' ')[0];
            });
          }
          console.log(result.data.content);
          return {
            data: result.data.content,
            total: result.data.totalElements,
            success: result.success,
          };
        }}
        columns={columns}
        scroll={{ x: 800, y: 350 }}
        rowSelection={{}}
      />

      <ModalForm
        visible={modalVisit}
        title={formTitle}
        form={form}
        onFinish={addErrorFile}
        modalProps={{
          destroyOnClose: true,
          onCancel: () => {
            setModalVisit(false);
          },
        }}
        initialValues={{
          errorReportId: errorRecord.id,
        }}
      >
        <ProFormText
          name="errorReportId"
          label="异常处理编号"
          disabled
          rules={[{ required: true, message: 'Please input your errorReportId!' }]}
        />

        <ProFormItem
          name="file"
          label="文件上传"
          rules={[{ required: true, message: 'Please input your fileCode!' }]}
        >
          <Upload
            file-list="fileList"
            onChange={onFilesChange} //通过覆盖默认的上传行为，可以自定义自己的上传实现
            showUploadList={true}
            beforeUpload={handleBeforeUpload}
            multiple
          >
            <Button className="standProduct_UploadStyle" icon={<UploadOutlined />}>
              上传文件
            </Button>
          </Upload>
        </ProFormItem>
      </ModalForm>
    </PageHeaderWrapper>
  );
};
export default ErrorReportFileInfo;
